import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { Ref } from 'vue'
import type { UserListType } from '@/typings/customerType'
import { getUsersApi } from '@/api/userApi'

// 元组
type userListType = [
  Ref<number>,
  Ref<UserListType[]>,
  Ref<number>,
  (page: number) => Promise<void>
]

const useUserList = (): userListType => {
  const router = useRouter()
  const route = useRoute()

  const data = ref<UserListType[]>([])
  const total = ref(0)

  const currentPage = computed(() => {
    return route.query.page ?  +route.query.page : 1
  })

  const loadData = async (page: number) => {
    router.replace(`?page=${page}`)
    let ret = await getUsersApi(page)
    if (ret.code === 0) {
      data.value = ret.data.users
      total.value = ret.data.total
    }
  }
  onMounted(() => {
    loadData(currentPage.value)
  })
  return [currentPage, data, total, loadData]
}

export default useUserList
